package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.MarketAdminMapper;
import com.cskaoyan.mapper.MarketPermissionMapper;
import com.cskaoyan.mapper.MarketPermissionTypeMapper;
import com.cskaoyan.mapper.MarketRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Fyy
 * @since 2022/12/30 22:36
 */

@Service
public class AuthServiceImpl implements AuthService{
    @Autowired
    MarketRoleMapper roleMapper;
    @Autowired
    MarketPermissionMapper permissionMapper;
    @Autowired
    MarketPermissionTypeMapper permissionTypeMapper;
    @Autowired
    MarketAdminMapper adminMapper;

    /**
     * 管理员权限信息
     * @param marketAdmin
     * @return
     */
    @Override
    public InfoData info(MarketAdmin marketAdmin) {
        //获取角色id
        Integer[] roleIds = marketAdmin.getRoleIds();
        MarketPermissionExample permissionExample = new MarketPermissionExample();
        //判断角色id是否为空,不为空则给example赋值
        if (!ObjectUtils.isEmpty(roleIds)) {
            permissionExample.createCriteria().andRoleIdIn(Arrays.asList(roleIds));
        }
        //查询符合条件的权限
        List<MarketPermission> permissionList = permissionMapper.selectByExample(permissionExample);
        List<String> permList = new ArrayList<>();
        //封装权限list
        for (MarketPermission permission : permissionList) {
            permList.add(permission.getPermission());
        }
        MarketPermissionTypeExample typeExample = new MarketPermissionTypeExample();
        //判断权限是否为空
        if (!ObjectUtils.isEmpty(permList)){
            typeExample.createCriteria().andNameIn(permList);
        }
        //根据权限列表获取并封装返回值所需要的权限列表
        List<MarketPermissionType> typeList = permissionTypeMapper.selectByExample(typeExample);
        List<String> list = new ArrayList<>();
        for (MarketPermissionType permissionType : typeList) {
            list.add(permissionType.getApi());
        }
        //获得管理员角色名
        MarketRoleExample example = new MarketRoleExample();
        if (!ObjectUtils.isEmpty(roleIds)) {
            example.createCriteria().andIdIn(Arrays.asList(roleIds));
        }
        List<MarketRole> roles = roleMapper.selectByExample(example);
        //封装返回值
        List<String> nameList = new ArrayList<>();
        for (MarketRole role : roles) {
            nameList.add(role.getName());
        }
        //进一步封装返回值
        InfoData authInfoVo = new InfoData();
        authInfoVo.setRoles(nameList);
        authInfoVo.setPerms(list);
        return authInfoVo;
    }

    @Override
    public void update(MarketAdmin marketAdmin) {
        adminMapper.updateByPrimaryKeySelective(marketAdmin);
    }
}
